﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace Sustainalytics.Synchronization.BusinessLogic
{
    [HubName("syncHub")]
    public class SyncHub : Hub
    {
        /// <summary>
        /// Context instance to access client connections to broadcast to
        /// </summary>
        public static IHubContext HubContext
        {
            get 
            {
                return GlobalHost.ConnectionManager.GetHubContext<SyncHub>();
            }
        }
        
        public void StartManualSync(List<SyncStepDescription> steps)
        {
            Globals.Sync.Start(steps);
        }

        public void CancelSync()
        {
            Globals.Sync.Cancel();
        }

        public void Send(string message)
        {
            Clients.All.addMessage(message);
        }


        public object GetState()
        {
            return new { State = Globals.Sync.GetLastSession() };
        }

        public bool IsSynchronizing()
        {
            return Globals.Sync.IsSynchronizing();
        }


        public object GetSyncSteps()
        {
            var steps = Globals.Sync.GetSteps();
            return new
            {
                Items = steps
            };
        }

        public override Task OnConnected()
        {
            SetClientData();
            return base.OnConnected();
        }

        private void SetClientData()
        {
            Clients.All.machineName(Globals.Sync.GetMachineName());
            Clients.All.isSyncAutomatic(Globals.Sync.IsSyncAutomatic());
            Clients.All.serviceStatus(Globals.Sync.ServiceStatus());
            Clients.All.lastSessionStatus(Globals.Sync.GetLastSessionStatus());
            Clients.All.isSynchronizing(Globals.Sync.IsSynchronizing());
            Clients.All.errorPolicy(Globals.Sync.CurrentErrorPolicy());
            Clients.All.lastDatabaseGroup(Globals.Sync.LastDatabaseGroup());
            Clients.All.currentDatabaseGroup(Globals.Sync.CurrentDatabaseGroup());
            Clients.All.nextAutoStart(Globals.Sync.NextAutoStart());
            Clients.All.skipCloning(Globals.Sync.SkipCloning());
        }

        public override Task OnReconnected()
        {
            SetClientData();
            return base.OnReconnected();
        }


        

    }


    
}
